package com.yzdbx.task;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.RandomUtil;
import com.yzdbx.utils.DbUtil;
import com.yzdbx.utils.GenUtil;

import java.math.BigDecimal;
import java.sql.*;
import java.util.*;
import java.util.stream.Collectors;

import static com.yzdbx.task.PurchaseRunnable.GEN_PURCHASE_IDS;
import static com.yzdbx.task.SalefOrderRunnable.GEN_ORDER_IDS;
import static com.yzdbx.utils.DbUtil.getMaxId;

/**
 * @BelongsProject: SERVEVICE-DATA-GEN
 * @BelongsPackage: com.yzdbx.task
 * @Author: lk
 * @CreateTime: 2025-05-14
 * @Description: TODO
 * @Version: 1.0
 */
public class PurchaseShouHuoRunnable implements Exe {

    private Connection connection;
    private static final int BATCH_SIZE = 3;


    public PurchaseShouHuoRunnable(Connection connection) {
        this.connection = connection;
    }

    public static final ThreadLocal<List<Integer>> FAHUO_IDS = new ThreadLocal<>();

    @Override
    public boolean execute(int count) {
        //拿到生成的采购订单明细
        List<Integer> purchaseIds = GEN_PURCHASE_IDS.get();
        int batchCount = 0;
        if (CollectionUtil.isEmpty(purchaseIds)) return Boolean.FALSE;

        List<Integer> huoshouIds = new ArrayList<>(purchaseIds.size());
        boolean originalAutoCommit = true;

        try {
            // 保存原始自动提交状态
            originalAutoCommit = connection.getAutoCommit();
            connection.setAutoCommit(false);

            int daohuoId = getMaxId(connection, "purchaseOfManifests");
            int ckdId = getMaxId(connection, "ck03Listing");
            int ckmxId = getMaxId(connection, "ck04ListOfEntriesListOfEntries");

            // 准备批量插入语句
            String manifestSql = "insert into purchaseOfManifests (id,purchaseOfManifestNumber,dateOfArrival,consignee,clientInformation,totalArrivals,amountOfGoodsToBeDelivered,synchronisingFolderFailedSS,created,approvalStatus,associatedPurchaseOrderInformati) values (?,?,?,?,?,?,?,?,?,?,?)";
            String ckmxSql = "insert into ck04ListOfEntriesListOfEntries(id,productInformation,numberOfEntries,linkToList) values (?,?,?,?)";
            String ckdSql = "insert into ck03Listing (id,repositoryNumber,operator,repositoryDate,approvalStatus,associatedSuppliers,documentType) values (?,?,?,?,?,?,?)";

            try (PreparedStatement manifestStatement = connection.prepareStatement(manifestSql);
                 PreparedStatement ckmxStatement = connection.prepareStatement(ckmxSql);
                 PreparedStatement ckdStatement = connection.prepareStatement(ckdSql)) {


                for (int i = 1; i <= purchaseIds.size(); i++) {
                    final int currentIndex = i - 1;
                    int curId = daohuoId + i;
                    String daohuodanhao = GenUtil.getNo("CGDH", i);
                    
                    //查询采购订单
                    Map<String, Object> saleOrder = DbUtil.getById(connection, "cgPurchaseOrderForms", purchaseIds.get(currentIndex));
                    
                    //查询采购订单明细
                    List<LinkedHashMap<String, Object>> details;
                    try (PreparedStatement statement = connection.prepareStatement("select * from breakdownOfPurchaseOrders where associatedPurchaseOrders = ?")) {
                        statement.setInt(1, purchaseIds.get(currentIndex));
                        ResultSet resultSet = statement.executeQuery();
                        details = DbUtil.resultSetToList(resultSet);
                    }

                    List<LinkedHashMap<String, Object>> associatedPurchase = details.stream()
                            .filter(cur -> cur.get("associatedPurchaseOrders").equals(purchaseIds.get(currentIndex)))
                            .collect(Collectors.toList());

                    int totalArrivals = 0;
                    BigDecimal totalAmount = BigDecimal.ZERO;

                    // 创建入库明细
                    for (int j = 1; j <= associatedPurchase.size(); j++) {
                        LinkedHashMap<String, Object> orderDetail = associatedPurchase.get(j - 1);
                        int quantity = Integer.parseInt(orderDetail.get("procurementVolume").toString());
                        BigDecimal unitPrice = BigDecimal.valueOf(Double.parseDouble(orderDetail.get("unitPrice").toString()));
                        
                        totalArrivals += quantity;
                        totalAmount = totalAmount.add(unitPrice.multiply(BigDecimal.valueOf(quantity)));

                        int curCkmxId = ++ckmxId;
                        ckmxStatement.setInt(1, curCkmxId);
                        ckmxStatement.setInt(2, Integer.parseInt(orderDetail.get("procurementInformation").toString()));
                        ckmxStatement.setInt(3, quantity);
                        ckmxStatement.setInt(4, ckdId + i);
                        ckmxStatement.addBatch();
                    }

                    // 创建收货单
                    manifestStatement.setInt(1, curId);
                    manifestStatement.setString(2, daohuodanhao);
                    manifestStatement.setTimestamp(3, GenUtil.CUR_TIME_STAMP.get());
                    manifestStatement.setString(4, saleOrder.get("synchronisingFolderFailedSS").toString());
                    manifestStatement.setInt(5, Integer.parseInt(saleOrder.get("associatedSuppliers").toString()));
                    manifestStatement.setInt(6, totalArrivals);
                    manifestStatement.setBigDecimal(7, totalAmount);
                    manifestStatement.setString(8, saleOrder.get("synchronisingFolderFailedSS").toString());
                    manifestStatement.setTimestamp(9, GenUtil.CUR_TIME_STAMP.get());
                    manifestStatement.setString(10, "已通过");
                    manifestStatement.setInt(11, Integer.parseInt(saleOrder.get("id").toString()));
                    manifestStatement.addBatch();

                    // 创建入库单
                    ckdStatement.setInt(1, ckdId + i);
                    ckdStatement.setString(2, GenUtil.getNo("RK", i));
                    ckdStatement.setString(3, saleOrder.get("synchronisingFolderFailedSS").toString());
                    ckdStatement.setTimestamp(4, GenUtil.CUR_TIME_STAMP.get());
                    ckdStatement.setString(5, "已通过");
                    ckdStatement.setInt(6, Integer.parseInt(saleOrder.get("associatedSuppliers").toString()));
                    ckdStatement.setString(7, "采购入库");
                    ckdStatement.addBatch();

                    huoshouIds.add(curId);
                    batchCount++;

                    // 每BATCH_SIZE条记录执行一次批量插入
                    if (batchCount >= BATCH_SIZE) {
                        manifestStatement.executeBatch();
                        ckmxStatement.executeBatch();
                        ckdStatement.executeBatch();
                        connection.commit();
                        batchCount = 0;
                    }
                }

                // 执行剩余的批量插入
                if (batchCount > 0) {
                    manifestStatement.executeBatch();
                    ckmxStatement.executeBatch();
                    ckdStatement.executeBatch();
                    connection.commit();
                }

            }

        } catch (Exception e) {
            try {
                if (!connection.getAutoCommit()) {
                    connection.rollback();
                }
            } catch (SQLException ex) {
                throw new RuntimeException("回滚失败", ex);
            }
            throw new RuntimeException("数据生成失败", e);
        } finally {
            try {
                // 恢复原始自动提交状态
                connection.setAutoCommit(originalAutoCommit);
            } catch (SQLException e) {
                throw new RuntimeException("恢复自动提交状态失败", e);
            }
        }

        FAHUO_IDS.set(huoshouIds);
        return Boolean.TRUE;
    }
}
